import { convertKeysToCamelCase, convertKeysToSnakeCase } from '@/utils/formatters'
import axios, { AxiosError, type AxiosRequestConfig, type AxiosResponse, type InternalAxiosRequestConfig } from 'axios'
import qs from 'qs'

const axiosInstance = axios.create({
  baseURL: `${import.meta.env.BASE_URL}api`,
  timeout: 60000,
  paramsSerializer: params => {
    const filteredParams = Object.fromEntries(Object.entries(params).filter(([_, value]) => value !== '' && value != null))
    return qs.stringify(filteredParams, { arrayFormat: 'repeat' })
  }
})

axiosInstance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    if (config.params) config.params = convertKeysToSnakeCase(config.params)
    if (config.data) config.data = convertKeysToSnakeCase(config.data)
    return config
  },
  (error: AxiosError) => Promise.reject(error)
)

axiosInstance.interceptors.response.use(
  (response: AxiosResponse) => convertKeysToCamelCase(response.data),
  error => Promise.reject(new Error(error.response?.data?.detail ?? error.message ?? 'Unknown error'))
)

const request = <T = unknown>(url: string, options?: AxiosRequestConfig): Promise<T> => axiosInstance({ url, ...options })

export { request }
